package com.sike.netty.im.server.handler;

import com.sike.netty.im.common.command.JoinGroupRequestCommand;
import com.sike.netty.im.common.command.JoinGroupResponseCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import com.sike.netty.im.server.service.BeanFactory;
import com.sike.netty.im.server.service.GroupService;
import com.sike.netty.im.server.service.SessionService;
import com.sike.netty.im.server.service.UserInfoCache;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Map;

/**
 * 加入群聊
 *
 * @author chenssy
 * @date 2023/09/20
 */
public class JoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestCommand> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestCommand msg) throws Exception {
        // 获取当前用户名
        SessionService sessionService = (SessionService) BeanFactory.getServiceBean(SessionService.class);
        String userId = sessionService.getUserIdByChannel(ctx.channel());
        String userName = UserInfoCache.getUserInfoByUserId(userId).getUserName();

        // 加入群聊
        GroupService groupService = (GroupService) BeanFactory.getServiceBean(GroupService.class);
        Map<String,Object> joinGroupMap = groupService.joinGroup(msg.getGroupId(), userName);

        // 通知客户端
        JoinGroupResponseCommand responseCommand = new JoinGroupResponseCommand();
        responseCommand.setGroupName(joinGroupMap.get("groupName").toString());
        responseCommand.setMemberList((List<String>) joinGroupMap.get("memberList"));
        Message message = MessageBuilder.buildMessage(responseCommand,null,userId);
        ctx.channel().writeAndFlush(message);
    }
}
